package orm.rzdata.dao.impl;

import orm.rzdata.dao.BaseDAO;
import orm.rzdata.utils.DBUtils;
import orm.rzdata.utils.Tools;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author com.ymy.hadoop
 * @date 2018/12/16 12:07
 */
public class BaseDAOImpl implements BaseDAO {

    public <T> Serializable save(T t) {
        // insert into wh_user(name,age,birth_day) values(?,?,?);
        StringBuilder builder = new StringBuilder("insert into ");
        String table = Tools.getTable(t.getClass());

        builder.append(table).append("(");

        Class<?> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields){
            // 属性不为id的情况(属性为set、get方法后的字母，并把开头字母转换成小写)
            if (!field.getName().equals("id")){
                String column = Tools.getColumn(field);
                builder.append(column).append(",");
            }
        }
        builder.deleteCharAt(builder.toString().length()-1).append(") values (");

        for (Field field : fields){
            if (!field.getName().equals("id")){
                builder.append("?,");
            }
        }
        builder.deleteCharAt(builder.toString().length()-1).append(")");
//        System.out.println(builder.toString());

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int index = 1;
        try {
            connection = DBUtils.getConnection();
            pstmt = connection.prepareStatement(builder.toString(),new String[]{"id"});
            for (Field field : fields) {
                if (!field.getName().equals("id")) {
                    String methodName = Tools.getMethod(field, "get");
                    Method method = clazz.getDeclaredMethod(methodName);
                    // method.invoke(t)，执行后获取到的值，为执行method方法后的返回值
                    Object obj = method.invoke(t);
//                    System.out.println("method.invoke后方法的返回值" + obj);
                    // 逐个放到sql语句中去(替换values(?,?,?) 问号占位符的位置)
                    pstmt.setObject(index++, obj);
                }
            }
                int rowCount = pstmt.executeUpdate();
//                System.out.println("rowCount = " + rowCount);

                if(rowCount > 0) {
                    rs = pstmt.getGeneratedKeys();
                    rs.next();
                    return (Serializable)rs.getObject(1);
                }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            DBUtils.close(connection);
        }
        return null;
    }
}
